<?php
namespace App\Api\Controllers\Changsha;


use Illuminate\Support\Facades\Validator;

class BaseController extends \App\Api\Controllers\BaseController
{
    // 表单提交字符集编码
    public $postCharset = "UTF-8";
    private $fileCharset = "UTF-8";
    public $rsaPrivateKeyFilePath = "";
    public $pri_key = "MIIEowIBAAKCAQEAgKVnr7iDqV46hPEqvtmjr2x/Js1+NVahC14xvo3BWWGsl0jLtlDxAcrQfHfqr5MpepaweSUlIBHwWV4E10cx+e4tV0e4J3ip3HrYSCCk0CGZuMzls9S7B0UqUxilmaYqtVIFcWSyQAVxW8CQw7BGcLaID6mZ4j3SqATZ27OiW6OXyIH3JrVwxlinE0+nXRNgNQDXL2vpW0txmfDySEooXHlkEUfVX5CJclHYcpmmOjXlBPehPQjDgYOurI3eDP5CxzfMpkIrr6D1YhyfilxAXgN0mfS2ESEAlsZDdt0zbDjVZh3kngPH9wO903mtAAQTwio1peJDncDA9V4QHgKwowIDAQABAoIBAAF34dMTnA0W0jwqNH6xJTkfV+QtfD9HmdbzYEX4gDhw8PNZFVojWlzW38JL7BXM7DBGAAWh8uaGzeN3Oz7pxRxBJ6tTWjq5Gdc2X7mTBc6KU6LUU9rVlrzigTUpltpGFz6yjPVaXN52MXEGpaBWJreqnarwGJ2IbxsT0xi62COLmk0mJm6LTDENIZz7+3YB41Bq8flLT/0W5YuR8vmaUbRsR5Tq4sIEc+O5pxbWyMqbwgDTiAXMUonSUz6g3hk/itAn+M5QQaCCwN1WaxBA5s87nygz8sXYP7WOdifpuNyQ6Br7OMuY1b9l0mZNHxj5N4cUcxVFoYiMKjtzhkEYoeECgYEAwao34I79QFLe2lM+jBRVgHQw1jfDtLdvF0iuBDLH8vUmiblb4YmQ9kbcwobT16pAk9f9z/Yj3D3nttyPhT7QUZFvMYNFmIo+a5ujcRhfYUUxri4fAbe2W1WEGlpnY//TfREM7Pk+/xtLj1rSUk7ABq9KfPulhVerVF1Sm8Zrb88CgYEAqg21AzB0LDmGk+XaMeA8vL1NIb24McO6mHJKRdozC2VGh8tw2uKW4SQVqZpchYeObxfqd9aE9ZbSXMp6rPVRg8trL5LhNylcl28alZLa97FQRcv4R5X8mFDxfSzuBAfa2Q4b/uSNkKZ59k0CmPLekyHwxyJ2pkFlPi4IIf2ecu0CgYB4BOyCHzt1rKXted9uYn+mjtthNsfzbCbNsD4f3fSqbiFHAvedK2sKJVpUt8f7hMhml1n1kp4gtMCwQ7oyIn5pvo7BiZAM+8e5WogM48TgfEhQoMaYgujha3rl9hbTE01W2cU/6yuOX7URD4D+f01kFyg7kpy+qVlFfFxgq7QTYwKBgBNBfBbBXNZJKUkEBQISzy3cDajdb8cKz81FW82vGIqYzDTCP6Q5djZGPMG4vfNM1z8TKTSqsOGSU324W83L9ZAD774yVphFcbugFBWNzIexp1JP92w7up+QwteWx9ji/tAHPfpN7Q3NHBBcxgeFsNheRoJ2D5Nh4lH5KmiW7GM9AoGBAKO64tDzSq0PKwzKmjMSgKVyT2vpxtD22oUGz6lA6r5/2yONGvkJPM1U2luv2QLS17/6LVFRctunrj8ysPQfnM8vZx8rcGYUpyDF+cJCfS53vBvoFwRb5bfdxrjOCkfIQfh3I5cyzSmq8ZHmihmO7BtTJXPZscK3E652MAq4mywt";
    public $BC = "https://pbank.bankofchangsha.com/directBank/paygate/v0/orderPay.do";
    public $ORDERQUERY = "https://pbank.bankofchangsha.com/directBank/paygate/v0/orderQueryWithSign.do";
    public $REFUND = "https://pbank.bankofchangsha.com/directBank/paygate/h5/thirdpartyRefund.do";


    //参数拼接
    public function getSignContent($params)
    {
        ksort($params);

        $stringToBeSigned = "";
        $i = 0;
        foreach ($params as $k => $v) {
            if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
                // 转换成目标字符集
                $v = $this->characet($v, $this->postCharset);

                if ($i == 0) {
                    $stringToBeSigned .= "$k" . "=" . "$v";
                } else {
                    $stringToBeSigned .= "&" . "$k" . "=" . "$v";
                }
                $i++;
            }
        }

        unset ($k, $v);

        return $stringToBeSigned;
    }


    /**
     * 转换字符集编码
     * @param $data
     * @param $targetCharset
     * @return string
     */
    function characet($data, $targetCharset)
    {
        if (!empty($data)) {
            $fileType = $this->fileCharset;
            if (strcasecmp($fileType, $targetCharset) != 0) {
                $data = mb_convert_encoding($data, $targetCharset);
                //$data = iconv($fileType, $targetCharset.'//IGNORE', $data);
            }
        }

        return $data;
    }


    /**
     * 校验$value是否非空
     *  if not set ,return true;
     *    if is null , return true;
     **/
    protected function checkEmpty($value)
    {
        if (!isset($value))
            return true;
        if ($value === null)
            return true;
        if (trim($value) === "")
            return true;

        return false;
    }


    /**
     * curl发送数据
    */
    static function curl($data, $url)
    {
        //启动一个CURL会话
        $ch = curl_init();
        // 设置curl允许执行的最长秒数
        curl_setopt($ch, CURLOPT_TIMEOUT, 120);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        // 获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        //发送一个常规的POST请求。
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        //要传送的所有数据
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        // 执行操作
        $res = curl_exec($ch);
        $response = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if ($res == NULL) {
            curl_close($ch);
            return false;
        } else if ($response != "200") {
            curl_close($ch);
            return false;
        }

        curl_close($ch);
        return $res;
    }


    function curl_get($url)
    {
        $ch = curl_init();

        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//绕过ssl验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        //执行并获取HTML文档内容
        $output = curl_exec($ch);

        //释放curl句柄
        curl_close($ch);
        return $output;
    }


    /**
     * 校验必填字段
     */
    public function check_required($check, $data)
    {
        $rules = [];
        $attributes = [];
        foreach ($data as $k => $v) {
            $rules[$k] = 'required';
            $attributes[$k] = $v;
        }

        $messages = [
            'required' => ':attribute不能为空',
        ];
        $validator = Validator::make($check, $rules, $messages, $attributes);
        $message = $validator->getMessageBag();

        return $message->first();
    }


    public function curl_form($url, $data)
    {
        $headers = array('Content-Type: application/x-www-form-urlencoded');
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
        //  curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data)); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        $result = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl); //捕抓异常
        }
        curl_close($curl); // 关闭CURL会话

        return $result;
    }


    /**
     * http的curl 方法post请求接口
     * @param string $url
     * @param string $post_data
     * @return string
     */
    function http_curl($url, $post_data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // post数据
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($post_data))
        );
        $output = curl_exec($ch);
        curl_close($ch);

        //返回数据
        return $output;
    }


    public function rsaSign($content)
    {
        $pri_key = $this->pri_key;

        $pri_key_f = $this->formatPriKey($pri_key);
        $privKeyId = openssl_pkey_get_private($pri_key_f);
        $signature = '';
        openssl_sign($content, $signature, $privKeyId, OPENSSL_ALGO_SHA256);
        openssl_free_key($privKeyId);

        //base64编码
        return base64_encode($signature);
    }


    public function sign($data, $signType = "RSA")
    {
        if ($this->checkEmpty($this->rsaPrivateKeyFilePath)) {
            $priKey = $this->pri_key;
            $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
                wordwrap($priKey, 64, "\n", true) .
                "\n-----END RSA PRIVATE KEY-----";
        } else {
            $priKey = file_get_contents($this->rsaPrivateKeyFilePath);
            $res = openssl_get_privatekey($priKey);
        }

        ($res) or die('您使用的私钥格式错误，请检查RSA私钥配置');

        if ("RSA2" == $signType) {
            openssl_sign($data, $sign, $res, OPENSSL_ALGO_SHA256);
        } else {
            openssl_sign($data, $sign, $res);
        }

        if (!$this->checkEmpty($this->rsaPrivateKeyFilePath)) {
            openssl_free_key($res);
        }

        $sign = bin2hex($sign);

        return strtoupper($sign);
    }


    public function strToHex($string)
    {
        $hex = "";
        for ($i = 0; $i < strlen($string); $i++)
            $hex .= dechex(ord($string[$i]));
        $hex = strtoupper($hex);
        return $hex;
    }


    function rsaSign1($content)
    {
        $pri_key = $this->pri_key;
        $pri_key_f = $this->formatPriKey($pri_key);
        $res = openssl_get_privatekey($pri_key_f);
        openssl_sign($content, $sign, $res);
        openssl_free_key($res);
        //base64编码
        $sign = base64_encode($sign);

        return $sign;
    }


    /**
     * 格式化rsa私钥
     * @param $priKey
     * @return string
     * User: WangMingxue
     * Email cumt_wangmingxue@126.com
     */
    public function formatPriKey($priKey)
    {
        $fKey = "-----BEGIN PRIVATE KEY-----\n";
        $len = strlen($priKey);
        for ($i = 0; $i < $len;) {
            $fKey = $fKey . substr($priKey, $i, 64) . "\n";
            $i += 64;
        }
        $fKey .= "-----END PRIVATE KEY-----";
        return $fKey;
    }


}
